<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>Document</title>
        <script>!function(t,e){var n=t.documentElement,i="orientationchange"in window?"orientationchange":"resize",o=function(){var t=n.clientWidth,e=750;t&&(t>=e?n.style.fontSize="100px":n.style.fontSize=100*(t/e)+"px")};o(),t.addEventListener&&(e.addEventListener(i,o,!1),t.addEventListener("DOMContentLoaded",o,!1))}(document,window);</script>
        <link rel="stylesheet" href="../css/base.css" />
        <link rel="stylesheet" href="../css/common.css" />
    </head>
    <body>
        <h1>HTML5 file API加canvas实现图片前端JS压缩并上传</h1>
        <p><a href="https://www.zhangxinxu.com/wordpress/2017/07/html5-canvas-image-compress-upload/">来源</a></p>
        <input id="file" type="file">
        <canvas></canvas>
        <script>
            var eleFile = document.querySelector('#file');

            // 压缩图片需要的一些元素和对象
            var reader = new FileReader(), img = new Image();

            // 选择的文件对象
            var file = null;

            // 缩放图片需要的canvas
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');

            // base64地址图片加载完毕后
            img.onload = function () {
                // 图片原始尺寸
                var originWidth = this.width;
                var originHeight = this.height;
                // 最大尺寸限制
                var maxWidth = 400, maxHeight = 400;
                // 目标尺寸
                var targetWidth = originWidth, targetHeight = originHeight;
                // 图片尺寸超过400x400的限制
                if (originWidth > maxWidth || originHeight > maxHeight) {
                    if (originWidth / originHeight > maxWidth / maxHeight) {
                        // 更宽，按照宽度限定尺寸
                        targetWidth = maxWidth;
                        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                    } else {
                        targetHeight = maxHeight;
                        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                    }
                }
                    
                // canvas对图片进行缩放
                canvas.width = targetWidth;
                canvas.height = targetHeight;
                // 清除画布
                context.clearRect(0, 0, targetWidth, targetHeight);
                // 图片压缩
                context.drawImage(img, 0, 0, targetWidth, targetHeight);
                // canvas转为blob并上传
                canvas.toBlob(function (blob) {
                    // 图片ajax上传
                    var xhr = new XMLHttpRequest();
                    // 文件上传成功
                    xhr.onreadystatechange = function() {
                        if (xhr.status == 200) {
                            // xhr.responseText就是返回的数据
                        }
                    };
                    // 开始上传
                    xhr.open("POST", 'upload.php', true);
                    xhr.send(blob);    
                }, file.type || 'image/png');
            };

            // 文件base64化，以便获知图片原始尺寸
            reader.onload = function(e) {
                img.src = e.target.result;
            };
            eleFile.addEventListener('change', function (event) {
                file = event.target.files[0];
                // 选择的文件是图片
                if (file.type.indexOf("image") == 0) {
                    reader.readAsDataURL(file);    
                }
            });
        </script>
    </body>
</html>